<template>
    <div>
        <navigation-bar :customTitle="curTitle">
            <div class="searchContent">
                <el-input
                    v-model="userName"
                    placeholder="请输入方案名称"
                    size="mini"
                    style="width: 150px; margin-right: 10px; margin-left: 10px"
                ></el-input>
                <custom-button type="search" style="margin-right: 10px" @searchClick="searchClick"></custom-button>
                <custom-button type="reset" style="margin-right: 10px" @resetClick="resetClick"></custom-button>
                <custom-button type="add" @addClick="addClick"></custom-button>
            </div>
        </navigation-bar>

        <div>
            <table-index
                :dataSource="dataSource"
                :tableColumns="tableColumns"
                :btnList="btnList"
                @viewRow="viewRow"
                @editRow="editRow"
                @deleteRow="deleteRow"
                selection
                @handleSelectionChange="handleSelectionChange"
                :height="secondTableHeight"
                :showPage="false"
            ></table-index>
            <Spin size="large" fix v-if="spinShow" class="demo-spin">
                <Icon type="ios-loading" size="18" class="demo-spin-icon-load"></Icon>
                <div>数据加载中...</div>
            </Spin>
        </div>

        <kongtiaoDetail
            v-if="showAdd"
            @dialogClose="dialogClose"
            title="空调温控方案配置"
            :wkfaId="wkfaId"
            :isFirst="false"
        ></kongtiaoDetail>
    </div>
</template>

<script>
import {userManageForm} from '@/assets/form/managementCenter/systemManage/userManage'
import {resetPwdForm} from '@/assets/form/managementCenter/systemManage/resetPwd'
import customDialog from '@/components/customComponents/customDialog'
import customButton from '@/components/customComponents/customForm/customButton'
import formIndex from '@/components/customComponents/customForm/formIndex'
import tableIndex from '@/components/customComponents/customeTable/iviewTable/singleViewTable'
import navigationBar from '@/components/customComponents/managementCenter/navigationBarCustomTitle'
import {AjaxCommon, AjaxCommonExcelDownload} from '@/libs/apiCommon'
import {CardId} from '@/libs/cardId'
import {PopupCommon} from '@/libs/popupCommon'
import {Utility} from '@/libs/utility'
import addAirPlan from './addAirPlan.vue'
import kongtiaoDetail from '../../../../qyjn/components/threeDevice/kongtiaoDetail'
import pubsub from 'pubsub-js'
export default {
    components: {
        navigationBar,
        customButton,
        tableIndex,
        customDialog,
        formIndex,
        addAirPlan,
        kongtiaoDetail
    },
    data() {
        return {
            wkfaId: '',
            showAdd: false,
            spinShow: false,
            treeList: [],
            dde: 0,
            sde: 0,
            // 操作类型（ 0核销 1下发）
            oprType: '0',
            optionValue: 'name',
            options: [
                {
                    value: 'name',
                    label: '登录名'
                },
                {
                    value: 'realname',
                    label: '真实姓名'
                }
            ],
            orgInfo: {},
            secondTableHeight: 80,
            selectUserList: [],
            userName: null,
            status: '',
            curTitle: '空调温控方案',
            statusList: Utility.getDictList('status'),
            // table 相关参数  begin
            dataSource: [],
            tableColumns: [
                {
                    type: 'index',
                    width: 60,
                    align: 'center',
                    fixed: 'left'
                },
                {
                    key: 'SCHE_NAME',
                    title: '方案名称',
                    width: 100,
                    align: 'center',
                    fixed: 'left'
                },

                // 制冷开启温度 2
                // 制热开启温度 3
                {
                    key: 'kqwd',
                    title: '开启温度（℃）',
                    align: 'center',
                    children: [
                        {
                            key: 'kqwdzhire',
                            title: '制热',
                            align: 'center',
                            width: 68
                        },
                        {
                            key: 'kqwdzhileng',
                            title: '制冷',
                            align: 'center',
                            width: 68
                        }
                    ]
                },

                // 制冷开机温度 4
                // 制热开机温度 5
                {
                    key: 'kjwd',
                    title: '开机温度（℃）',
                    align: 'center',
                    children: [
                        {
                            key: 'kjwdzhire',
                            title: '制热',
                            align: 'center',
                            width: 68
                        },
                        {
                            key: 'kjwdzhileng',
                            title: '制冷',
                            align: 'center',
                            width: 68
                        }
                    ]
                },

                // 制冷关机温度 6
                // 制热关机温度 7
                {
                    key: 'gjwd',
                    title: '关机温度（℃）',
                    align: 'center',
                    children: [
                        {
                            key: 'gjwdzhire',
                            title: '制热',
                            align: 'center',
                            width: 68
                        },
                        {
                            key: 'gjwdzhileng',
                            title: '制冷',
                            align: 'center',
                            width: 68
                        }
                    ]
                },

                // 夏季判断温度 9
                // 冬季判断温度 10
                {
                    key: 'pdwd',
                    title: '判断温度（℃）',
                    align: 'center',
                    children: [
                        {
                            key: 'pdwdxiaji',
                            title: '夏季',
                            align: 'center',
                            width: 68
                        },
                        {
                            key: 'pdwddongji',
                            title: '冬季',
                            align: 'center',
                            width: 68
                        }
                    ]
                },

                // 夏天目标温度值 11
                // 冬季目标温度值 12
                {
                    key: 'mbwdz',
                    title: '目标温度值（℃）',
                    align: 'center',
                    children: [
                        {
                            key: 'mbwdzxiaji',
                            title: '夏季',
                            align: 'center',
                            width: 68
                        },
                        {
                            key: 'mbwdzdongji',
                            title: '冬季',
                            align: 'center',
                            width: 68
                        }
                    ]
                },

                // 临时设定时间 8
                {
                    key: 'lssdsj',
                    title: '临时设定时间（分）',
                    // slot: 'sfyx',
                    width: 100
                },

                // 温度模式开启温度使能 13
                {
                    key: 'wdmskqwdsn',
                    title: '温度模式开启温度使能',
                    // slot: 'sfyx',
                    width: 120
                },
                // 温度使能运行方式 14
                {
                    key: 'wdsnyxfs',
                    title: '温度使能运行方式',
                    // slot: 'sfyx',
                    width: 100
                },
                // 温度模式开关机控制 15
                {
                    key: 'wdmskgjkz',
                    title: '温度模式开关机控制',
                    // slot: 'sfyx',
                    width: 110
                },
                // {
                //     key: 'zdkz',
                //     title: '自动控制',
                //     align: 'center',
                //     width: 150,
                //     slot: 'zdkz'
                // },

                // {
                //     key: 'sfyx',
                //     title: '是否有效',
                //     slot: 'sfyx',
                //     width: 100
                // },
                // {
                //     key: 'sfkqsdkz',
                //     title: '是否开启时段控制',
                //     slot: 'sfyx',
                //     width: 150
                // },
                {
                    key: 'zhczr',
                    title: '最后操作人',
                    width: 110
                },
                {
                    key: 'czsj',
                    title: '操作时间',
                    width: 180
                },
                // {
                //     key: 'bz',
                //     title: '备注',
                //     width: 100
                // },
                {
                    title: '操作',
                    slot: 'action',
                    width: 140,
                    align: 'center',
                    fixed: 'right'
                }
            ],
            btnList: ['edit', 'delete'],
            pageSize: 20,
            pageCount: 100,
            pageNo: 1,
            // table 相关参数  end

            // 弹窗是否显示
            dialogShow: false,
            // 弹窗标题 (新增修改不同)
            dialogTitle: '',

            // form的配置信息
            formConfig: null,
            type: 'add',

            formResetConfig: resetPwdForm(''),
            acGuid: ''
        }
    },
    created() {
        this.formConfig = userManageForm('add')
    },
    methods: {
        exportXls() {
            let title = '定额管理'
            const treeList = this.treeList
            if (treeList.length == 0) {
                PopupCommon.notify('info', '请勾选左侧建筑树')
                return
            }
            const id = treeList.map((t) => t.id).toString()
            let params = `/api/QuotaAllot/ExportProducts?buildIds=${id}`
            if (this.userName) {
                params += `&ac_name=${this.userName}`
            }
            AjaxCommonExcelDownload(params).then(
                (response) => {
                    const blob = new Blob([response.data], {
                        type: 'application/vnd.ms-excel'
                    })
                    const link = document.createElement('a')
                    link.href = window.URL.createObjectURL(blob)
                    link.download = title + '.xls'
                    link.click()
                },
                (error) => {
                    console.log(error.message)
                }
            )
            // AjaxCommon(params, 'get', null).then(
            //     (response) => {
            //         const blob = new Blob([response.data], {
            //             type: 'application/vnd.ms-excel'
            //         })
            //         const link = document.createElement('a')
            //         link.href = window.URL.createObjectURL(blob)
            //         link.download = title + '.xls'
            //         link.click()
            //     },
            //     (error) => {
            //         console.log(error.message)
            //     }
            // )
        },
        changeMoeny(e) {
            if (e > 10000) {
                this.dde = 10000
            }
            if (e < 0) {
                this.dde = 0
            }
        },
        changeMoeny1(e) {
            if (e > 10000) {
                this.sde = 10000
            }
            if (e < 0) {
                this.sde = 0
            }
        },
        importClick() {
            this.resetClick()
        },
        getHeight() {
            // 1825
            this.secondTableHeight = document.getElementsByClassName('rightContentHref')[0].clientHeight - 85
        },
        handleSelectionChange(d) {
            this.selectUserList = d
        },
        formInputChange(e) {
            if (e.filedName == 'idCard') {
                const data = CardId.getInfoByCardId(e.value)
                if (data) {
                    let newData = e.allData
                    newData['birthday'] = data.birthday
                    newData['sex'] = data.sex
                    this.$refs.form.changeFormValue(newData)
                }
            }
        },
        submit(d) {
            let self = this

            if (d.UserGUID) {
                AjaxCommon('/api/User/EditUser', 'post', d).then((res) => {
                    if (res?.data?.Code == 200) {
                        PopupCommon.notify('success', '编辑成功')
                        self.initPage(self.treeList)
                        self.dialogClose()
                    } else {
                        const msg = res?.data?.Message
                        if (msg) {
                            PopupCommon.notify('error', msg)
                        }
                    }
                })
            } else {
                d.Enable = '1'
                delete d.UserGUID
                // 根据类型调用不同接口
                let url = '/api/User/AddUser'
                AjaxCommon(url, 'post', d).then((res) => {
                    if (res?.data?.Code == 200) {
                        PopupCommon.notify('success', '新增成功')
                        self.initPage(self.treeList)
                        self.dialogClose()
                    } else {
                        const msg = res?.data?.Message
                        if (msg) {
                            PopupCommon.notify('error', msg)
                        }
                    }
                })
            }
        },
        dialogClose(isTrue) {
            if (isTrue) {
                this.searchClick()
            }
            this.showAdd = false
        },
        searchClick() {
            this.pageNo = 1
            this.initPage(this.treeList)
        },
        saveData() {
            if (this.selectUserList.length == 0) {
                PopupCommon.notify('info', '请至少选择一个用户')
                return
            }
            const title = this.oprType == '0' ? '核销' : '下发'
            if (this.dde == 0 && this.sde == 0) {
                PopupCommon.notify('info', '水定额和电定额的值加起来要大于0')
                return
            }
            const self = this
            // 核销
            PopupCommon.confirm(`电定额为：${this.dde}，水定额为：${this.sde}，是否进行${title}?`)
                .then(() => {
                    // api/QuotaAllot/DeducteAmount
                    AjaxCommon(`api/QuotaAllot/DeducteAmount`, 'post', {
                        //  账户GUID，多个用，分隔
                        ac_guids: self.selectUserList.map((t) => t.ac_guid).toString(),
                        /**
                         *  配发金额（如有多个需要|分隔） 如免费电金额、免费水金额  5|10或5|0
                         */
                        amount: `${self.dde}|${self.sde}`,
                        operType: self.oprType
                    }).then((res) => {
                        if (res?.data?.Code == 200) {
                            PopupCommon.notify('success', title + '成功')
                            self.initPage(self.treeList)
                        } else {
                            const msg = res?.data?.Message
                            if (msg) {
                                let errTitle = ''
                                if (typeof msg == 'object') {
                                    msg.map((t) => {
                                        errTitle += `${t.ac}：${t.msg}，`
                                    })
                                    errTitle = errTitle.substring(0, errTitle.length - 1)
                                } else {
                                    errTitle = msg
                                }
                                PopupCommon.notify('error', errTitle)
                            }
                        }
                    })
                })
                .catch(() => {
                    // 这里尽量写下，否则会报警告异常。
                    console.log('已取消删除')
                })
        },
        resetClick() {
            this.userName = ''
            this.dde = 0
            this.sde = 0
            this.pageNo = 1
            this.searchClick()
        },
        addClick() {
            // this.formConfig = userManageForm('add')
            // let formConfigItem = this.formConfig
            // formConfigItem.map((t) => {
            //     Object.keys(t).map((res) => {
            //         if (res == 'fieldName') {
            //             t.filedValue = ''
            //         }
            //     })
            // })
            // this.formConfig = formConfigItem
            // this.type = 'add'
            // this.dialogTitle = '新增'
            // this.dialogShow = true
            this.wkfaId = ''
            this.showAdd = true
        },
        // 分页点击事件
        pageChange(p) {
            this.pageNo = p
            this.initPage(this.treeList)
        },
        deleteRow(d) {
            AjaxCommon(`/api/TimePlan/DeleteAirTimePlan/${d.LIST_GUID}`, 'post', {}).then((res) => {
                if (res?.data?.Code == 200) {
                    PopupCommon.notify('error', '删除成功')
                    this.initPage()
                } else {
                    PopupCommon.notify('error', '删除失败')
                }
            })
        },
        editRow(d) {
            this.wkfaId = d.LIST_GUID
            this.showAdd = true
        },
        viewRow(d) {
            // this.acGuid = d.ac_guid
            // this.dialogTitle = `【${d.ac_name}】查看`
            // this.dialogShow = true
            this.showAdd = true
        },
        getValue(d) {
            if (d == '' || d == 255 || d == null) {
                return '--'
            } else {
                return d
            }
        },
        // 初始化事件
        initPage() {
            const params = `/api/TimePlan/GetAirTimePlan`
            AjaxCommon(params, 'get', null).then((res) => {
                if (res?.data?.Code == 200) {
                    const data = res?.data.Message
                    pubsub.publish('fangAnChange', data)
                    const newData = data.map((t) => {
                        const options = t.OPTIONS?.split('|')
                        t.kqwdzhileng = this.getValue(options?.[2])
                        t.kqwdzhire = this.getValue(options?.[3])
                        t.kjwdzhire = this.getValue(options?.[5])
                        t.kjwdzhileng = this.getValue(options?.[4])
                        t.gjwdzhileng = this.getValue(options?.[6])
                        t.gjwdzhire = this.getValue(options?.[7])
                        t.pdwdxiaji = this.getValue(options?.[9])
                        t.pdwddongji = this.getValue(options?.[10])
                        t.mbwdzxiaji = this.getValue(options?.[11])
                        t.mbwdzdongji = this.getValue(options?.[12])
                        t.lssdsj = this.getValue(options?.[8])

                        // 温度模式开启温度使能   0,关闭；01，开启，控制器默认值为1；不设置传255
                        t.wdmskqwdsn = options?.[13] == 1 ? '开启' : options?.[13] === 0 ? '关闭' : '--'
                        // 1,按天使能；2，按时段使能控制器默认值为1；不设置传255
                        t.wdsnyxfs = options?.[14] == 1 ? '按天使能' : options?.[14] === 2 ? '按时段使能' : '--'
                        // 温度模式开关机控制1,制冷/制热开机控制；2，制冷/制热关机控制；3，制冷/制热开关机控制；默认为2;不设置传255
                        t.wdmskgjkz =
                            options?.[15] == 1
                                ? '制冷/制热开机控制'
                                : options?.[15] === 2
                                ? '制冷/制热关机控制'
                                : options?.[15] === 3
                                ? '制冷/制热开关机控制'
                                : '--'
                        t.zhczr = t.OPER_USER
                        t.czsj = t.OPER_TIME
                        // 人感延迟时间  0
                        // 人感人数 1
                        // 制冷开启温度 2
                        // 制热开启温度 3
                        // 制冷开机温度 4
                        // 制热开机温度 5
                        // 制冷关机温度 6
                        // 制热关机温度 7
                        // 临时设定时间 8
                        // 夏季判断温度 9
                        // 冬季判断温度 10
                        // 夏天目标温度值 11
                        // 冬季目标温度值 12
                        // 温度模式开启温度使能 13
                        // 温度使能运行方式 14
                        // 温度模式开关机控制 15
                        //  this.workMode
                        //     controlValue += workMode.indexOf('调温') != -1 ? 1 : 0
                        // controlValue += workMode.indexOf('人感') != -1 ? 1 : 0
                        // controlValue += workMode.indexOf('温度') != -1 ? 1 : 0
                        // controlValue += workMode.indexOf('时间') != -1 ? 1 : 0
                        // controlValue += workMode.indexOf('手动') != -1 ? 1 : 0
                        // controlValue += workMode.indexOf('计量') != -1 ? 1 : 0
                        // controlValue += workMode.indexOf('断电') != -1 ? 1 : 0
                        // controlValue += workMode.indexOf('机房省电') != -1 ? 1 : 0
                        // controlValue += workMode.indexOf('定时') != -1 ? 1 : 0

                        //              "OPTIONS": "255|255|28|28|26|20|28|10|30|255|255|255|255|1|1|2|100000000",
                        // "DAY_SCHE": "1-1,01:03,04:00/2-FF,FF:FF,FF:FF/3-0,04:04,13:04/4-FF,FF:FF,FF:FF/5-FF,FF:FF,FF:FF/6-FF,FF:FF,FF:FF/7-FF,FF:FF,FF:FF",
                        return t
                    })
                    this.dataSource = newData
                } else {
                    pubsub.publish('fangAnChange', [])
                    PopupCommon.notify('error', res?.data?.msg)
                }
            })
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.getHeight()
        })

        /*窗口自适应，关键代码*/
        window.onresize = () => {
            this.getHeight()
        }

        this.initPage()
    }
}
</script>

<style scoped lang="scss">
.demo-spin {
    background-color: rgba(0, 0, 0, 0.2);
}
.demo-spin-icon-load {
    animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
    from {
        transform: rotate(0deg);
    }
    50% {
        transform: rotate(180deg);
    }
    to {
        transform: rotate(360deg);
    }
}
</style>
